const config = require('../config')
const Koa = require('koa')
const Router = require('koa-router')
const static = require('koa-static')
const koaBody = require('koa-body')
const views = require('koa-views')
const fs = require('fs')
const path = require('path')
const app = new Koa()
const uploadImg = require('../utils/upload')

// const bodyparser = Bodyparser()

app.use(static('/'))
app.use(views(__dirname,'/static/pages', {
    extension: 'ejs'
}))

const router = new Router()

router.get('/get',async (ctx) => {
    console.log(ctx.query)
    // get query
    let params = JSON.stringify(ctx.query)
    ctx.type = 'application/json;charset=utf-8'
    ctx.type = 'json'
    ctx.response.set('Content-type', 'application/json;charset=utf-8')
    ctx.body = params;
})

router.get('/getCreateUserView',async (ctx)=>{
    // 当GET请求时候返回表单页面
    let title = '创建新用户'
    await ctx.render('index', {
        title,
    })
})

router.post('/postCreateUserData', async (ctx, next) => {
    const file = ctx.request.body.files.file; // 获取上传文件
    const ext = file.name.split('.').pop(); // 获取上传文件扩展名
    ctx.body = await uploadImg(file.path, Math.random().toString() + '.' + ext)
    // 文件写入本地
    // const reader = fs.createReadStream(file.path); // 创建可读流
    // const ext = file.name.split('.').pop(); // 获取上传文件扩展名
    // const upStream = fs.createWriteStream(`upload/${Math.random().toString()}.${ext}`); // 创建可写流
    // reader.pipe(upStream); // 可读流通过管道写入可写流
})

router.get('getUser','/',ctx => {
    // 当GET请求时候返回表单页面
    let data = {
        name: 'congcong.rao',
        age: 24,
        sex: 'girl'
    }
    ctx.type = 'application/json;charset=utf-8'
    ctx.type = 'json'
    ctx.response.set('Content-type', 'application/json;charset=utf-8')
    ctx.body = data;
})

router.get('/api',ctx => {
    // 当GET请求时候返回表单页面
    let j = {
        a: '1',
        b: '2',
        c: '3'
    }
    let jsonstr = JSON.stringify(j)
    ctx.type = 'text/javascript'
    ctx.body = jsonstr;
})

router.get('/404',ctx => {
    // 当GET请求时候返回表单页面
    // ctx.throw(500)
    ctx.body = '出错啦！';
})

app.use(koaBody({ multipart: true }));
app.use(router.routes())
app.use(router.allowedMethods())

app.listen(config.port, ()=>{
    console.log('service is 3000')
})